package com.virtualtrainer_01.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;

import com.virtualtrainer_01.model.Model;
import com.virtualtrainer_01.model.Training;

public class TrainingExerciseDB extends SQLiteDB {
	public static final String DATABASE_TABLE = "trainingexercise";
	public static final String KEY_ID = "_id";
	public static final String KEY_IDTRAINING = "idTraining";
	public static final String KEY_IDEXERCISE = "idExercise";

	public TrainingExerciseDB(Context c) {
		super(c, DATABASE_TABLE);
	}

	@Override
	public String getData() {

		String[] columns = new String[] { KEY_ID, KEY_IDTRAINING,
				KEY_IDEXERCISE };
		Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
				null, null);
		String result = "";

		int iRow = c.getColumnIndex(KEY_ID);
		int iIdTr = c.getColumnIndex(KEY_IDTRAINING);
		int iIdEx = c.getColumnIndex(KEY_IDEXERCISE);

		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
			result = result + c.getString(iRow) + " " + c.getString(iIdTr)
					+ " " + c.getString(iIdEx) + " ";
		return result;
	}

	@Override
	public long createEntry(Model entry) {
		Training t = (Training) entry;
		ExerciseDB edb = new ExerciseDB(this.ourContext);
		TrainingDB tdb = new TrainingDB(this.ourContext);
		edb.open();
		tdb.open();
		ContentValues cv = new ContentValues();
		for (int i = 0; i < t.getExerciseList().size(); i++) {
			try {
				cv.put(KEY_IDEXERCISE, edb.getId(t.getExerciseList().get(i)));
				cv.put(KEY_IDTRAINING, tdb.getId(entry));
				ourDatabase.insert(DATABASE_TABLE, null, cv);
			} catch (SQLiteException e) {
				e.printStackTrace();
			}
		}
		edb.close();
		tdb.close();
		return 1;
	}

	public List<Integer> getIdExerciseList(int idTraining) {
		String sql = "SELECT "+KEY_IDEXERCISE+" FROM " + DATABASE_TABLE + " t where t." + KEY_IDTRAINING
				+ "=" + "'" + idTraining + "';";
		Cursor c = ourDatabase.rawQuery(sql, null);

		int iIdTr = c.getColumnIndex(KEY_IDEXERCISE);
		List<Integer> list = new ArrayList<Integer>();
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
			 list.add(Integer.parseInt(c.getString(iIdTr))) ;
		return list;
	}
}
